#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <functional>

using namespace std;
int defaultsock = -1;
using func_t = function<string(const string&)>;

class UdpServer
{
public:
    UdpServer(uint16_t port, func_t func, int sock = defaultsock) : _port(port),_func(func), _sockfd(sock)
    {
    }

    void InitServer()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            cerr << "socket create error" << endl;
            exit(1);
        }
        cout << "socket create success" << endl;

        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            cerr << "bind create error" << endl;
            exit(2);
        }
        cout << "bind create success" << endl;
    }

    void Start()
    {
        while (true)
        {
            char buffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                buffer[n] = 0;
                cout << "recvfrom: " << buffer << endl;

                string response = _func(buffer);
                sendto(_sockfd, response.c_str(), response.size(), 0, (struct sockaddr *)&peer, len);
            }
        }
    }

    ~UdpServer()
    {
    }

private:
    int _sockfd;
    uint16_t _port;
    func_t _func;
};